package cn.com.kh.lark;

import cn.com.kh.HttpClientProxy;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.util.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @projectName: ngsapitask-hst
 * @package: cn.com.kh
 * @className: larkMSGDev
 * @author: LiJT
 * @description: TODO
 * @date: 2023-09-20 16:56
 * @version: 1.0
 */
public class larkMSGDev {
    private static final Log log = LogFactory.getLog(larkMSGDev.class);
    // 飞书通知参数
    public static final String WebHookUrl = "https://open.feishu.cn/open-apis/bot/v2/hook/fa093cc5-e0ee-486d-a487-b296f2a1d76e?receive_id_type=email";
    public static final String WebHookKey = "x6qCreL64xDvow4nJzv8wd";

    public static void main(String[] args) throws Exception {


        int timestamp = (int) (System.currentTimeMillis() / 1000);
        log.debug("sendMessage timestamp:" + timestamp);

        String str = "";
        try {
            str = hmacSHA256(WebHookKey, String.valueOf(timestamp));
            System.out.println("加密后 =========>" + str);
            str = GenSign(WebHookKey, timestamp);
            System.out.println("加密后 =========>" + str);
        } catch (Exception e) {
            System.out.println("Error HmacSHA256 ===========>" + e.getMessage());
        }
    }


    public static boolean sendMessage(String msg) throws Exception {
        //请求的JSON数据
        JSONObject json = new JSONObject();
        json.put("msg_type", "text");
        JSONObject text = new JSONObject();
        text.put("text", "过河兵工单\n<at user_id=\"吕媛\">吕媛</at>");
        text.put("text", "【过河兵工单提醒\uD83D\uDCE2】\n#### 催单提醒  \n > 本次工单处理人@18948733947 @13229563780 @15820110636 @18118771463 @13824079580 @18871026107 \n - 工单编号：GD-202309270007 \n - 工单类型：咨询/出入金/eDDA授权 \n - 工单节点：技术跟进 \n - 创建人：霍伟健 \n - 创建时间：2023-09-27 15:05:38 \n");
        json.put("content", text);

        // 获取签名
        int timestamp = (int) (System.currentTimeMillis() / 1000);
        log.debug("sendMessage timestamp:" + timestamp);
        String sendSign = GenSign(WebHookKey, timestamp);
        log.debug("sendMessage sendSign:" + sendSign);
        json.put("timestamp", timestamp);
        json.put("sign", sendSign);
        log.debug("sendMessage Body:" + json);

        //发送post请求
        String result = HttpClientProxy.sendPost(WebHookUrl, json.toString(), "", 0);
        log.debug("sendMessage Result:" + result);

        JSONObject resJson = JSONObject.fromObject(result);

        if (resJson.getInt("StatusCode") == 0) {
            return true;
        } else {

            return false;
        }

    }

    private static String GenSign(String secret, int timestamp) throws NoSuchAlgorithmException, InvalidKeyException {
        //把timestamp+"\n"+密钥当做签名字符串
        String stringToSign = timestamp + "\n" + secret;
        //使用HmacSHA256算法计算签名
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(stringToSign.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(new byte[]{});
        return new String(Base64.encodeBase64(signData));
    }


    /**
     * HmacSHA256算法,返回的结果始终是32位
     *
     * @param key     加密的键，可以是任何数据
     * @param content 待加密的内容
     * @return 加密后的内容
     * @throws Exception
     */
    public static byte[] hmacSHA256(byte[] key, byte[] content) throws Exception {
        Mac hmacSha256 = Mac.getInstance("HmacSHA256");
        hmacSha256.init(new SecretKeySpec(key, 0, key.length, "HmacSHA256"));
        byte[] hmacSha256Bytes = hmacSha256.doFinal(content);
        return hmacSha256Bytes;
    }

    /**
     * 将加密后的字节数组转换成字符串
     *
     * @param b 字节数组
     * @return 字符串
     */
    public static String byteArrayToHexString(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toLowerCase();
    }

    /**
     * sha256_HMAC加密
     *
     * @param message 消息
     * @param secret  秘钥
     * @return 加密后字符串
     */
    public static String hmacSHA256(String secret, String message) throws Exception {
        String hash = "";
        Mac hmacSha256 = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
        hmacSha256.init(secret_key);
        byte[] bytes = hmacSha256.doFinal(message.getBytes());
        hash = byteArrayToHexString(bytes);
        return hash;
    }


}
